import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { TransformInterceptor } from './common/TransformInterceptor';
import { GlobalErrorFilter } from './common/GlobalErrorFilter';
import * as express from 'express';
import { NestExpressApplication } from '@nestjs/platform-express';
import { NestApplicationOptions } from '@nestjs/common';
import * as compression from 'compression';
import { join } from 'path';
import helmet from 'helmet';

function initAPP(app: NestExpressApplication): void {
  // swagger配置
  const config = new DocumentBuilder()
    .setTitle('希桐文化')
    .setDescription('The store clerk API description')
    .setVersion('2.0')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  // 设置 swagger 访问路径
  SwaggerModule.setup('/swagger-ui.html', app, document);
  // 统一处理返回格式
  app.useGlobalInterceptors(new TransformInterceptor())
  // 统一处理捕获异常
  app.useGlobalFilters(new GlobalErrorFilter());
  // 设置接受请求载荷
  const limit = '50mb';
  app.use(express.json({ limit }));
  app.use(express.urlencoded({ limit, extended: false }));
  // 开启允许跨域请求
  app.enableCors();
  // 开启压缩响应主体的大小，提高 Web 应用的速度
  app.use(compression())
  // 设置静态资源存储目录
  app.useStaticAssets(join(__dirname, '..', 'public'));
  // 设置网页存储目录
  app.setBaseViewsDir(join(__dirname, '..', 'views'));
  // 设置模板引擎，渲染HTML页面
  // app.setViewEngine('hbs');
  // 避免一些 Web 漏洞
  app.use(helmet());
}

async function bootstrap() {
  // 服务配置
  const config: NestApplicationOptions = {
    cors: true,
  }
  const app = await NestFactory.create<NestExpressApplication>(AppModule, config);
  initAPP(app)
  await app.listen(8000);
}

// 启动应用
bootstrap();
